<template>
  <div class="test-center">
    <NavBar />
    
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" icon="el-icon-arrow-left">返回</el-button>
        <h1>开发测试中心</h1>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="runAllTests" icon="el-icon-video-play">运行全部测试</el-button>
        <el-button @click="resetTests" icon="el-icon-refresh">重置</el-button>
      </div>
    </div>

    <!-- 测试概览 -->
    <div class="test-overview">
      <div class="overview-card">
        <div class="card-header">
          <h3>测试概览</h3>
          <el-tag :type="getOverallStatusType">{{ getOverallStatus }}</el-tag>
        </div>
        <div class="test-stats">
          <div class="stat-item">
            <div class="stat-number passed">{{ testStats.passed }}</div>
            <div class="stat-label">通过</div>
          </div>
          <div class="stat-item">
            <div class="stat-number failed">{{ testStats.failed }}</div>
            <div class="stat-label">失败</div>
          </div>
          <div class="stat-item">
            <div class="stat-number pending">{{ testStats.pending }}</div>
            <div class="stat-label">待测试</div>
          </div>
          <div class="stat-item">
            <div class="stat-number total">{{ testStats.total }}</div>
            <div class="stat-label">总计</div>
          </div>
        </div>
      </div>

      <div class="overview-card">
        <div class="card-header">
          <h3>应用信息</h3>
        </div>
        <div class="app-info">
          <div class="info-item">
            <span class="info-label">应用名称:</span>
            <span class="info-value">{{ appInfo.name }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">APP Key:</span>
            <span class="info-value">{{ appInfo.appkey }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">测试环境:</span>
            <el-tag size="small" :type="getEnvType">{{ appInfo.environment }}</el-tag>
          </div>
          <div class="info-item">
            <span class="info-label">SDK版本:</span>
            <span class="info-value">{{ appInfo.sdkVersion }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 功能测试 -->
    <div class="test-section">
      <div class="section-header">
        <h2>功能测试</h2>
        <el-button type="primary" size="small" @click="runFunctionTests" icon="el-icon-video-play">运行功能测试</el-button>
      </div>
      
      <div class="test-groups">
        <div class="test-group" v-for="(group, groupIndex) in functionTests" :key="groupIndex">
          <div class="group-header">
            <h4>{{ group.name }}</h4>
            <el-button 
              size="mini" 
              @click="runGroupTests(group)"
              :icon="getGroupIcon(group)"
            >
              {{ getGroupButtonText(group) }}
            </el-button>
          </div>
          
          <div class="test-items">
            <div 
              class="test-item" 
              v-for="(test, testIndex) in group.tests" 
              :key="testIndex"
              :class="getTestItemClass(test)"
            >
              <div class="test-header">
                <div class="test-info">
                  <div class="test-name">{{ test.name }}</div>
                  <div class="test-desc">{{ test.description }}</div>
                </div>
                <div class="test-actions">
                  <el-button 
                    size="mini" 
                    @click="runSingleTest(test)"
                    :icon="getTestIcon(test)"
                    :loading="test.status === 'running'"
                  >
                    {{ getTestButtonText(test) }}
                  </el-button>
                </div>
              </div>
              
              <div class="test-params" v-if="test.params">
                <div class="param-item" v-for="(param, paramIndex) in test.params" :key="paramIndex">
                  <span class="param-label">{{ param.label }}:</span>
                  <el-input 
                    v-model="param.value" 
                    size="mini" 
                    :placeholder="param.placeholder"
                    style="width: 200px"
                  />
                </div>
              </div>
              
              <div class="test-result" v-if="test.result">
                <div class="result-status" :class="test.result.status">
                  <i :class="getResultIcon(test.result.status)"></i>
                  {{ getResultText(test.result.status) }}
                </div>
                <div class="result-message">{{ test.result.message }}</div>
                <div class="result-details" v-if="test.result.details">
                  <pre>{{ test.result.details }}</pre>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 集成测试 -->
    <div class="test-section">
      <div class="section-header">
        <h2>集成测试</h2>
        <el-button type="primary" size="small" @click="runIntegrationTests" icon="el-icon-video-play">运行集成测试</el-button>
      </div>
      
      <div class="integration-tests">
        <div class="integration-item" v-for="(test, index) in integrationTests" :key="index">
          <div class="integration-header">
            <div class="integration-info">
              <h4>{{ test.name }}</h4>
              <p>{{ test.description }}</p>
            </div>
            <div class="integration-actions">
              <el-button 
                size="mini" 
                @click="runIntegrationTest(test)"
                :loading="test.status === 'running'"
              >
                {{ getIntegrationButtonText(test) }}
              </el-button>
            </div>
          </div>
          
          <div class="integration-steps" v-if="test.steps">
            <div 
              class="step-item" 
              v-for="(step, stepIndex) in test.steps" 
              :key="stepIndex"
              :class="getStepClass(step)"
            >
              <div class="step-number">{{ stepIndex + 1 }}</div>
              <div class="step-content">
                <div class="step-name">{{ step.name }}</div>
                <div class="step-status">
                  <i :class="getStepIcon(step)"></i>
                  {{ getStepStatusText(step) }}
                </div>
              </div>
            </div>
          </div>
          
          <div class="integration-result" v-if="test.result">
            <div class="result-summary" :class="test.result.status">
              <i :class="getResultIcon(test.result.status)"></i>
              {{ getResultText(test.result.status) }} - {{ test.result.message }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 性能测试 -->
    <div class="test-section">
      <div class="section-header">
        <h2>性能测试</h2>
        <el-button type="primary" size="small" @click="runPerformanceTests" icon="el-icon-video-play">运行性能测试</el-button>
      </div>
      
      <div class="performance-tests">
        <div class="performance-item" v-for="(test, index) in performanceTests" :key="index">
          <div class="performance-header">
            <div class="performance-info">
              <h4>{{ test.name }}</h4>
              <p>{{ test.description }}</p>
            </div>
            <div class="performance-actions">
              <el-button 
                size="mini" 
                @click="runPerformanceTest(test)"
                :loading="test.status === 'running'"
              >
                {{ getPerformanceButtonText(test) }}
              </el-button>
            </div>
          </div>
          
          <div class="performance-metrics" v-if="test.metrics">
            <div class="metric-item" v-for="(metric, metricIndex) in test.metrics" :key="metricIndex">
              <div class="metric-label">{{ metric.label }}</div>
              <div class="metric-value" :class="getMetricClass(metric)">
                {{ metric.value }}
                <span class="metric-unit" v-if="metric.unit">{{ metric.unit }}</span>
              </div>
              <div class="metric-status">
                <el-progress 
                  :percentage="getMetricProgress(metric)" 
                  :color="getMetricColor(metric)"
                  :show-text="false"
                />
              </div>
            </div>
          </div>
          
          <div class="performance-result" v-if="test.result">
            <div class="result-grade" :class="test.result.grade">
              <i :class="getGradeIcon(test.result.grade)"></i>
              {{ getGradeText(test.result.grade) }}
            </div>
            <div class="result-summary">{{ test.result.summary }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 测试结果日志 -->
    <div class="test-section">
      <div class="section-header">
        <h2>测试日志</h2>
        <el-button size="small" @click="clearLogs" icon="el-icon-delete">清空日志</el-button>
      </div>
      
    <div class="test-logs">
        <div class="log-controls">
          <el-radio-group v-model="logLevel" size="small" @change="filterLogs">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="info">信息</el-radio-button>
            <el-radio-button label="success">成功</el-radio-button>
            <el-radio-button label="warning">警告</el-radio-button>
            <el-radio-button label="error">错误</el-radio-button>
          </el-radio-group>
          <el-button size="small" @click="exportLogs" icon="el-icon-download">导出日志</el-button>
        </div>
        
        <div class="log-container">
          <div 
            class="log-item" 
            v-for="(log, index) in filteredLogs" 
            :key="index"
            :class="`log-${log.level}`"
          >
            <div class="log-time">{{ log.time }}</div>
            <div class="log-level">
              <el-tag size="mini" :type="getLogType(log.level)">{{ log.level.toUpperCase() }}</el-tag>
            </div>
            <div class="log-message">{{ log.message }}</div>
          </div>
          
          <div v-if="filteredLogs.length === 0" class="log-empty">
            <i class="el-icon-info"></i>
            暂无日志信息
          </div>
        </div>
      </div>
    </div>

    <!-- 自定义参数测试 -->
    <div class="test-section">
      <div class="section-header">
        <h2>自定义参数测试</h2>
        <el-button type="primary" size="small" @click="saveCustomParams" icon="el-icon-save">保存参数</el-button>
        <el-button size="small" @click="loadCustomParams" icon="el-icon-refresh">加载参数</el-button>
      </div>
      
      <div class="custom-params-container">
        <div class="params-input">
          <h4>参数设置</h4>
          <div class="param-editor">
            <el-input
              type="textarea"
              v-model="customParams"
              :rows="8"
              placeholder='请输入自定义参数，格式为JSON对象，例如：
{
  "user_id": "12345",
  "channel": "test_channel",
  "campaign": "test_campaign",
  "referrer": "test_user"
}'
            />
          </div>
          <div class="param-actions">
            <el-button size="small" @click="validateParams" icon="el-icon-check">验证格式</el-button>
            <el-button size="small" @click="clearParams" icon="el-icon-delete">清空</el-button>
          </div>
        </div>
        
        <div class="params-preview">
          <h4>参数预览</h4>
          <div class="preview-content">
            <div v-if="parsedParams" class="param-list">
              <div class="param-item" v-for="(value, key) in parsedParams" :key="key">
                <span class="param-key">{{ key }}:</span>
                <span class="param-value">{{ value }}</span>
              </div>
            </div>
            <div v-else class="preview-empty">
              <i class="el-icon-info"></i>
              请输入有效的JSON格式参数
            </div>
          </div>
        </div>
      </div>
      
      <div class="params-test">
        <h4>参数传递测试</h4>
        <div class="test-methods">
          <div class="test-method">
            <h5>分享链接生成测试</h5>
            <p>测试使用自定义参数生成分享链接</p>
            <el-button size="small" @click="testShareLink" icon="el-icon-link">生成分享链接</el-button>
            <div v-if="shareLinkResult" class="result-container">
              <div class="result-link">
                <el-input v-model="shareLinkResult.link" readonly />
                <el-button size="small" @click="copyLink" icon="el-icon-copy">复制</el-button>
              </div>
              <div class="result-params">
                <strong>包含参数：</strong>
                <pre>{{ shareLinkResult.params }}</pre>
              </div>
            </div>
          </div>
          
          <div class="test-method">
            <h5>SDK参数传递测试</h5>
            <p>测试SDK是否正确传递自定义参数</p>
            <el-button size="small" @click="testSDKParams" icon="el-icon-share">测试SDK传递</el-button>
            <div v-if="sdkTestResult" class="result-container">
              <div class="result-status" :class="sdkTestResult.status">
                <i :class="getResultIcon(sdkTestResult.status)"></i>
                {{ getResultText(sdkTestResult.status) }}
              </div>
              <div class="result-message">{{ sdkTestResult.message }}</div>
            </div>
          </div>
          
          <div class="test-method">
            <h5>参数持久化测试</h5>
            <p>测试参数是否正确保存和读取</p>
            <el-button size="small" @click="testParamPersistence" icon="el-icon-document">测试持久化</el-button>
            <div v-if="persistenceResult" class="result-container">
              <div class="result-comparison">
                <div class="comparison-item">
                  <strong>原始参数：</strong>
                  <pre>{{ persistenceResult.original }}</pre>
                </div>
                <div class="comparison-item">
                  <strong>读取参数：</strong>
                  <pre>{{ persistenceResult.retrieved }}</pre>
                </div>
                <div class="comparison-result" :class="persistenceResult.status">
                  <i :class="getResultIcon(persistenceResult.status)"></i>
                  {{ persistenceResult.match ? '参数匹配' : '参数不匹配' }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 落地页自动跳转模拟 -->
    <div class="test-section">
      <div class="section-header">
        <h2>落地页自动跳转模拟</h2>
        <el-button type="primary" size="small" @click="simulateLandingJump" icon="el-icon-position">开始模拟</el-button>
      </div>
      <div class="test-logs">
        <div class="log-container">
          <div class="log-item">模拟将使用 Web SDK 的 autoJump 进行打开或跳转，具体行为受平台/浏览器限制。</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import NavBar from '@/components/NavBarEnhanced.vue';

export default {
  components: {
    NavBar
  },
  data() {
    return {
      appInfo: {
        name: '测试应用',
        appkey: 'test_app_key_12345',
        environment: '测试环境',
        sdkVersion: '1.0.0'
      },
      
      testStats: {
        passed: 0,
        failed: 0,
        pending: 0,
        total: 0
      },
      
      logLevel: 'all',
      logs: [],
      
      // 自定义参数测试
      customParams: '',
      parsedParams: null,
      shareLinkResult: null,
      sdkTestResult: null,
      persistenceResult: null,
      
      functionTests: [
        {
          name: '设备指纹测试',
          tests: [
            {
              name: '基础设备指纹',
              description: '测试基础设备指纹采集功能',
              status: 'pending',
              params: [
                { label: '用户代理', value: '', placeholder: '浏览器User-Agent' },
                { label: '屏幕分辨率', value: '', placeholder: '例如: 1920x1080' }
              ],
              result: null
            },
            {
              name: 'Canvas指纹',
              description: '测试Canvas指纹生成算法',
              status: 'pending',
              result: null
            }
          ]
        },
        {
          name: '归因测试',
          tests: [
            {
              name: '精确归因',
              description: '测试精确匹配归因算法',
              status: 'pending',
              result: null
            },
            {
              name: '模糊归因',
              description: '测试模糊匹配归因算法',
              status: 'pending',
              result: null
            }
          ]
        }
      ],
      
      integrationTests: [
        {
          name: '完整归因流程',
          description: '测试从链接点击到安装归因的完整流程',
          status: 'pending',
          steps: [
            { name: '生成分享链接', status: 'pending' },
            { name: '模拟用户点击', status: 'pending' },
            { name: '记录设备指纹', status: 'pending' },
            { name: '模拟APP安装', status: 'pending' },
            { name: '匹配归因', status: 'pending' },
            { name: '验证结果', status: 'pending' }
          ],
          result: null
        }
      ],
      
      performanceTests: [
        {
          name: '归因性能测试',
          description: '测试归因接口的响应时间和并发处理能力',
          status: 'pending',
          metrics: [
            { label: '平均响应时间', value: 0, unit: 'ms', threshold: 100, status: 'pending' },
            { label: '99分位响应时间', value: 0, unit: 'ms', threshold: 200, status: 'pending' },
            { label: '并发处理能力', value: 0, unit: 'req/s', threshold: 1000, status: 'pending' },
            { label: '内存使用率', value: 0, unit: '%', threshold: 80, status: 'pending' }
          ],
          result: null
        }
      ]
    };
  },
  
  computed: {
    getOverallStatus() {
      if (this.testStats.failed > 0) return '部分失败';
      if (this.testStats.passed === this.testStats.total && this.testStats.total > 0) return '全部通过';
      if (this.testStats.running > 0) return '测试中';
      return '待测试';
    },
    
    getOverallStatusType() {
      if (this.testStats.failed > 0) return 'danger';
      if (this.testStats.passed === this.testStats.total && this.testStats.total > 0) return 'success';
      if (this.testStats.running > 0) return 'info';
      return 'info';
    },
    
    getEnvType() {
      return this.appInfo.environment.includes('测试') ? 'warning' : 'success';
    },
    
    filteredLogs() {
      if (this.logLevel === 'all') return this.logs;
      return this.logs.filter(log => log.level === this.logLevel);
    }
  },
  
  mounted() {
    this.initTestStats();
    this.addLog('info', '测试中心初始化完成');
  },
  
  methods: {
    initTestStats() {
      let total = 0;
      let passed = 0;
      let failed = 0;
      let pending = 0;
      
      // 统计功能测试
      this.functionTests.forEach(group => {
        group.tests.forEach(test => {
          total++;
          if (test.status === 'passed') passed++;
          else if (test.status === 'failed') failed++;
          else pending++;
        });
      });
      
      // 统计集成测试
      this.integrationTests.forEach(test => {
        total++;
        if (test.status === 'passed') passed++;
        else if (test.status === 'failed') failed++;
        else pending++;
      });
      
      // 统计性能测试
      this.performanceTests.forEach(test => {
        total++;
        if (test.status === 'passed') passed++;
        else if (test.status === 'failed') failed++;
        else pending++;
      });
      
      this.testStats = { total, passed, failed, pending };
    },
    
    addLog(level, message) {
      const time = new Date().toLocaleTimeString('zh-CN');
      this.logs.unshift({ time, level, message });
      if (this.logs.length > 1000) {
        this.logs = this.logs.slice(0, 1000);
      }
    },
    
    async runAllTests() {
      this.addLog('info', '开始运行全部测试...');
      await this.runFunctionTests();
      await this.runIntegrationTests();
      await this.runPerformanceTests();
      this.addLog('success', '全部测试运行完成');
    },
    
    async runFunctionTests() {
      this.addLog('info', '开始运行功能测试...');
      for (const group of this.functionTests) {
        await this.runGroupTests(group);
      }
    },
    
    async runIntegrationTests() {
      this.addLog('info', '开始运行集成测试...');
      for (const test of this.integrationTests) {
        await this.runIntegrationTest(test);
      }
    },
    
    async runPerformanceTests() {
      this.addLog('info', '开始运行性能测试...');
      for (const test of this.performanceTests) {
        await this.runPerformanceTest(test);
      }
    },
    
    async runGroupTests(group) {
      this.addLog('info', `开始运行测试组: ${group.name}`);
      for (const test of group.tests) {
        await this.runSingleTest(test);
      }
    },
    
    async runSingleTest(test) {
      test.status = 'running';
      this.addLog('info', `开始测试: ${test.name}`);
      
      try {
        // 模拟测试执行
        await this.delay(Math.random() * 2000 + 1000);
        
        // 模拟测试结果 (80%成功率)
        const success = Math.random() > 0.2;
        
        if (success) {
          test.status = 'passed';
          test.result = {
            status: 'passed',
            message: '测试通过，功能正常',
            details: JSON.stringify({
              executionTime: Math.floor(Math.random() * 100 + 50) + 'ms',
              testData: '测试数据验证通过'
            }, null, 2)
          };
          this.addLog('success', `测试通过: ${test.name}`);
        } else {
          test.status = 'failed';
          test.result = {
            status: 'failed',
            message: '测试失败，请检查相关功能',
            details: '错误详情：功能异常或数据不匹配'
          };
          this.addLog('error', `测试失败: ${test.name}`);
        }
      } catch (error) {
        test.status = 'failed';
        test.result = {
          status: 'failed',
          message: '测试执行异常',
          details: error.message
        };
        this.addLog('error', `测试异常: ${test.name} - ${error.message}`);
      }
      
      this.initTestStats();
    },
    
    async runIntegrationTest(test) {
      test.status = 'running';
      this.addLog('info', `开始集成测试: ${test.name}`);
      
      try {
        // 重置步骤状态
        test.steps.forEach(step => step.status = 'running');
        
        // 逐步执行
        for (let i = 0; i < test.steps.length; i++) {
          await this.delay(Math.random() * 1000 + 500);
          test.steps[i].status = 'passed';
          this.addLog('info', `完成步骤: ${test.steps[i].name}`);
        }
        
        test.status = 'passed';
        test.result = {
          status: 'passed',
          message: '集成测试通过，所有步骤正常完成'
        };
        this.addLog('success', `集成测试通过: ${test.name}`);
      } catch (error) {
        test.status = 'failed';
        test.result = {
          status: 'failed',
          message: '集成测试失败',
          details: error.message
        };
        this.addLog('error', `集成测试失败: ${test.name} - ${error.message}`);
      }
      
      this.initTestStats();
    },
    
    async runPerformanceTest(test) {
      test.status = 'running';
      this.addLog('info', `开始性能测试: ${test.name}`);
      
      try {
        // 模拟性能测试
        await this.delay(3000);
        
        // 生成随机性能数据
        test.metrics.forEach(metric => {
          switch (metric.label) {
            case '平均响应时间':
              metric.value = Math.floor(Math.random() * 150 + 30);
              break;
            case '99分位响应时间':
              metric.value = Math.floor(Math.random() * 300 + 80);
              break;
            case '并发处理能力':
              metric.value = Math.floor(Math.random() * 2000 + 500);
              break;
            case '内存使用率':
              metric.value = Math.floor(Math.random() * 60 + 20);
              break;
          }
          
          // 评估状态
          if (metric.value <= metric.threshold) {
            metric.status = 'passed';
          } else {
            metric.status = 'failed';
          }
        });
        
        // 总体评估
        const passedMetrics = test.metrics.filter(m => m.status === 'passed').length;
        const totalMetrics = test.metrics.length;
        
        if (passedMetrics === totalMetrics) {
          test.status = 'passed';
          test.result = {
            grade: 'excellent',
            summary: '性能优秀，所有指标均达标'
          };
        } else if (passedMetrics >= totalMetrics * 0.7) {
          test.status = 'passed';
          test.result = {
            grade: 'good',
            summary: '性能良好，大部分指标达标'
          };
        } else {
          test.status = 'failed';
          test.result = {
            grade: 'poor',
            summary: '性能不达标，需要优化'
          };
        }
        
        this.addLog('success', `性能测试完成: ${test.name}`);
      } catch (error) {
        test.status = 'failed';
        test.result = {
          grade: 'error',
          summary: '性能测试执行失败'
        };
        this.addLog('error', `性能测试失败: ${test.name} - ${error.message}`);
      }
      
      this.initTestStats();
    },
    
    resetTests() {
      // 重置所有测试状态
      this.functionTests.forEach(group => {
        group.tests.forEach(test => {
          test.status = 'pending';
          test.result = null;
        });
      });
      
      this.integrationTests.forEach(test => {
        test.status = 'pending';
        test.steps.forEach(step => step.status = 'pending');
        test.result = null;
      });
      
      this.performanceTests.forEach(test => {
        test.status = 'pending';
        test.metrics.forEach(metric => {
          metric.value = 0;
          metric.status = 'pending';
        });
        test.result = null;
      });
      
      this.initTestStats();
      this.addLog('info', '测试状态已重置');
    },
    
    filterLogs() {
      // 日志过滤逻辑已在computed中实现
    },
    
    clearLogs() {
      this.logs = [];
      this.addLog('info', '日志已清空');
    },
    
    exportLogs() {
      const logText = this.logs.map(log => 
        `[${log.time}] ${log.level.toUpperCase()}: ${log.message}`
      ).join('\n');
      
      const blob = new Blob([logText], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `test-logs-${new Date().toISOString().slice(0, 10)}.txt`;
      link.click();
      
      this.addLog('success', '日志导出成功');
    },
    
    // 辅助方法
    getTestItemClass(test) {
      return {
        'test-passed': test.status === 'passed',
        'test-failed': test.status === 'failed',
        'test-running': test.status === 'running',
        'test-pending': test.status === 'pending'
      };
    },
    
    getTestIcon(test) {
      if (test.status === 'running') return 'el-icon-loading';
      if (test.status === 'passed') return 'el-icon-check';
      if (test.status === 'failed') return 'el-icon-close';
      return 'el-icon-video-play';
    },
    
    getTestButtonText(test) {
      if (test.status === 'running') return '测试中';
      if (test.status === 'passed') return '重新测试';
      if (test.status === 'failed') return '重试';
      return '开始测试';
    },
    
    getGroupIcon(group) {
      const hasRunning = group.tests.some(t => t.status === 'running');
      const hasFailed = group.tests.some(t => t.status === 'failed');
      const allPassed = group.tests.every(t => t.status === 'passed');
      
      if (hasRunning) return 'el-icon-loading';
      if (hasFailed) return 'el-icon-close';
      if (allPassed) return 'el-icon-check';
      return 'el-icon-video-play';
    },
    
    getGroupButtonText(group) {
      const hasRunning = group.tests.some(t => t.status === 'running');
      const hasFailed = group.tests.some(t => t.status === 'failed');
      const allPassed = group.tests.every(t => t.status === 'passed');
      
      if (hasRunning) return '测试中';
      if (hasFailed) return '重试失败项';
      if (allPassed) return '重新测试';
      return '运行测试组';
    },
    
    getResultIcon(status) {
      const iconMap = {
        'passed': 'el-icon-check',
        'failed': 'el-icon-close',
        'warning': 'el-icon-warning',
        'error': 'el-icon-circle-close'
      };
      return iconMap[status] || 'el-icon-info';
    },
    
    getResultText(status) {
      const textMap = {
        'passed': '通过',
        'failed': '失败',
        'warning': '警告',
        'error': '错误'
      };
      return textMap[status] || '未知';
    },
    
    getStepClass(step) {
      return {
        'step-passed': step.status === 'passed',
        'step-failed': step.status === 'failed',
        'step-running': step.status === 'running',
        'step-pending': step.status === 'pending'
      };
    },
    
    getStepIcon(step) {
      if (step.status === 'passed') return 'el-icon-check';
      if (step.status === 'failed') return 'el-icon-close';
      if (step.status === 'running') return 'el-icon-loading';
      return 'el-icon-time';
    },
    
    getStepStatusText(step) {
      const textMap = {
        'passed': '已完成',
        'failed': '失败',
        'running': '进行中',
        'pending': '待执行'
      };
      return textMap[step.status] || '未知';
    },
    
    getIntegrationButtonText(test) {
      if (test.status === 'running') return '测试中';
      if (test.status === 'passed') return '重新测试';
      if (test.status === 'failed') return '重试';
      return '开始测试';
    },
    
    getPerformanceButtonText(test) {
      if (test.status === 'running') return '测试中';
      if (test.status === 'passed') return '重新测试';
      if (test.status === 'failed') return '重试';
      return '开始测试';
    },
    
    getMetricClass(metric) {
      return {
        'metric-good': metric.status === 'passed',
        'metric-bad': metric.status === 'failed'
      };
    },
    
    getMetricProgress(metric) {
      if (metric.status === 'pending') return 0;
      const ratio = metric.value / metric.threshold;
      return Math.min(ratio * 100, 100);
    },
    
    getMetricColor(metric) {
      if (metric.status === 'passed') return '#67c23a';
      if (metric.status === 'failed') return '#f56c6c';
      return '#909399';
    },
    
    getGradeIcon(grade) {
      const iconMap = {
        'excellent': 'el-icon-trophy',
        'good': 'el-icon-medal',
        'poor': 'el-icon-warning',
        'error': 'el-icon-circle-close'
      };
      return iconMap[grade] || 'el-icon-info';
    },
    
    getGradeText(grade) {
      const textMap = {
        'excellent': '优秀',
        'good': '良好',
        'poor': '较差',
        'error': '错误'
      };
      return textMap[grade] || '未知';
    },
    
    getLogType(level) {
      const typeMap = {
        'info': 'info',
        'success': 'success',
        'warning': 'warning',
        'error': 'danger'
      };
      return typeMap[level] || 'info';
    },
    
    delay(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    
    // 自定义参数相关方法
    validateParams() {
      try {
        if (!this.customParams.trim()) {
          this.parsedParams = null;
          this.addLog('warning', '参数内容为空');
          return;
        }
        
        const params = JSON.parse(this.customParams);
        if (typeof params !== 'object' || params === null) {
          throw new Error('参数必须是对象类型');
        }
        
        this.parsedParams = params;
        this.addLog('success', '参数格式验证通过');
      } catch (error) {
        this.parsedParams = null;
        this.addLog('error', `参数格式错误: ${error.message}`);
      }
    },
    
    clearParams() {
      this.customParams = '';
      this.parsedParams = null;
      this.addLog('info', '参数已清空');
    },
    
    saveCustomParams() {
      try {
        this.validateParams();
        if (!this.parsedParams) {
          return;
        }
        
        // 保存到本地存储
        localStorage.setItem('xapptool_custom_params', this.customParams);
        this.addLog('success', '自定义参数已保存到本地存储');
      } catch (error) {
        this.addLog('error', `保存参数失败: ${error.message}`);
      }
    },
    
    loadCustomParams() {
      try {
        const saved = localStorage.getItem('xapptool_custom_params');
        if (saved) {
          this.customParams = saved;
          this.validateParams();
          this.addLog('success', '已从本地存储加载自定义参数');
        } else {
          this.addLog('info', '本地存储中没有保存的参数');
        }
      } catch (error) {
        this.addLog('error', `加载参数失败: ${error.message}`);
      }
    },
    
    testShareLink() {
      try {
        this.validateParams();
        if (!this.parsedParams) {
          this.addLog('warning', '请先输入有效的自定义参数');
          return;
        }
        
        // 模拟生成分享链接
        const baseUrl = window.location.origin;
        const params = new URLSearchParams(this.parsedParams);
        const link = `${baseUrl}/landing?${params.toString()}`;
        
        this.shareLinkResult = {
          link: link,
          params: JSON.stringify(this.parsedParams, null, 2)
        };
        
        this.addLog('success', '分享链接生成成功');
      } catch (error) {
        this.addLog('error', `生成分享链接失败: ${error.message}`);
      }
    },
    
    copyLink() {
      if (this.shareLinkResult && this.shareLinkResult.link) {
        navigator.clipboard.writeText(this.shareLinkResult.link).then(() => {
          this.addLog('success', '链接已复制到剪贴板');
        }).catch(() => {
          this.addLog('error', '复制链接失败');
        });
      }
    },
    
    testSDKParams() {
      try {
        this.validateParams();
        if (!this.parsedParams) {
          this.addLog('warning', '请先输入有效的自定义参数');
          return;
        }
        
        // 模拟SDK参数传递测试
        if (!window.XappTool) {
          this.sdkTestResult = {
            status: 'failed',
            message: 'Web SDK未加载，无法测试参数传递'
          };
          this.addLog('error', 'Web SDK未加载');
          return;
        }
        
        // 模拟参数传递过程
        const sdk = new window.XappTool();
        const result = sdk.setCustomParams(this.parsedParams);
        
        if (result) {
          this.sdkTestResult = {
            status: 'passed',
            message: 'SDK参数传递测试通过，参数已正确设置'
          };
          this.addLog('success', 'SDK参数传递测试通过');
        } else {
          this.sdkTestResult = {
            status: 'failed',
            message: 'SDK参数传递失败'
          };
          this.addLog('error', 'SDK参数传递失败');
        }
      } catch (error) {
        this.sdkTestResult = {
          status: 'failed',
          message: `SDK参数测试异常: ${error.message}`
        };
        this.addLog('error', `SDK参数测试异常: ${error.message}`);
      }
    },
    
    testParamPersistence() {
      try {
        this.validateParams();
        if (!this.parsedParams) {
          this.addLog('warning', '请先输入有效的自定义参数');
          return;
        }
        
        // 模拟参数持久化测试
        const original = JSON.stringify(this.parsedParams);
        
        // 保存参数
        localStorage.setItem('test_params', original);
        
        // 读取参数
        const retrieved = localStorage.getItem('test_params');
        const parsedRetrieved = JSON.parse(retrieved);
        
        // 比较参数
        const match = JSON.stringify(this.parsedParams) === retrieved;
        
        this.persistenceResult = {
          original: JSON.stringify(this.parsedParams, null, 2),
          retrieved: JSON.stringify(parsedRetrieved, null, 2),
          status: match ? 'passed' : 'failed',
          match: match
        };
        
        if (match) {
          this.addLog('success', '参数持久化测试通过，保存和读取的参数完全一致');
        } else {
          this.addLog('error', '参数持久化测试失败，保存和读取的参数不匹配');
        }
        
        // 清理测试数据
        localStorage.removeItem('test_params');
        
      } catch (error) {
        this.persistenceResult = {
          status: 'failed',
          match: false
        };
        this.addLog('error', `参数持久化测试异常: ${error.message}`);
      }
    },
    async simulateLandingJump() {
      try {
        if (!window.XappTool) {
          this.addLog('warning', '未找到 Web SDK，全局对象 window.XappTool 不存在');
          return;
        }
        const sdk = new window.XappTool();
        await sdk.init({ app_key: 'test_app_key_12345' });
        this.addLog('info', 'SDK 初始化完成，开始模拟自动跳转');
        await sdk.autoJump({
          ios: { store: 'https://apps.apple.com/app/id000000', scheme: 'myapp://open', universal: 'https://example.com/open' },
          android: { store: 'https://play.google.com/store/apps/details?id=com.example.app', scheme: 'myapp://open' },
          harmony: { store: 'https://appgallery.huawei.com/#/app/C123456' },
          fallback: 'https://example.com/download',
          params: { from: 'test-center', ts: Date.now() }
        });
        this.addLog('success', '模拟自动跳转完成（具体行为依赖平台与浏览器限制）');
      } catch (e) {
        this.addLog('error', '模拟失败：' + e.message);
      }
    },
    
    goBack() {
      this.$router.push('/console');
    }
  }
};
</script>

<style scoped>
.test-center {
  padding: 0;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  background: white;
  padding: 1.5rem 2rem;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.header-left h1 {
  margin: 0;
  color: #303133;
  font-size: 1.5rem;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 1rem;
}

/* 测试概览 */
.test-overview {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.5rem;
  padding: 2rem;
}

.overview-card {
  background: white;
  border-radius: 0.5rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.card-header {
  padding: 1.5rem;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.test-stats {
  padding: 1.5rem;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1rem;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 0.3rem;
}

.stat-number.passed {
  color: #67c23a;
}

.stat-number.failed {
  color: #f56c6c;
}

.stat-number.pending {
  color: #909399;
}

.stat-number.total {
  color: #409eff;
}

.stat-label {
  color: #909399;
  font-size: 0.9rem;
}

.app-info {
  padding: 1.5rem;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #f0f2f5;
}

.info-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.info-label {
  color: #909399;
  font-size: 0.9rem;
}

.info-value {
  color: #303133;
  font-weight: 500;
}

/* 测试区域 */
.test-section {
  padding: 0 2rem 2rem;
}

.section-header {
  background: white;
  padding: 1.5rem;
  border-radius: 0.5rem 0.5rem 0 0;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1px;
}

.section-header h2 {
  margin: 0;
  color: #303133;
}

.test-groups {
  background: white;
  border-radius: 0 0 0.5rem 0.5rem;
  overflow: hidden;
}

.test-group {
  border-bottom: 1px solid #e4e7ed;
}

.test-group:last-child {
  border-bottom: none;
}

.group-header {
  padding: 1.5rem;
  background: #f8f9fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.group-header h4 {
  margin: 0;
  color: #303133;
}

.test-items {
  padding: 0 1.5rem;
}

.test-item {
  padding: 1.5rem 0;
  border-bottom: 1px solid #f0f2f5;
  transition: all 0.3s ease;
}

.test-item:last-child {
  border-bottom: none;
}

.test-item:hover {
  background: #fafbfc;
}

.test-item.test-passed {
  border-left: 4px solid #67c23a;
}

.test-item.test-failed {
  border-left: 4px solid #f56c6c;
}

.test-item.test-running {
  border-left: 4px solid #409eff;
  background: #f0f9ff;
}

.test-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;
}

.test-info {
  flex: 1;
}

.test-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 0.5rem;
}

.test-desc {
  color: #909399;
  font-size: 0.9rem;
}

.test-params {
  margin-bottom: 1rem;
}

.param-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 0.5rem;
}

.param-label {
  color: #606266;
  font-size: 0.9rem;
  min-width: 80px;
}

.test-result {
  background: #f8f9fa;
  border-radius: 0.5rem;
  padding: 1rem;
}

.result-status {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.result-status.passed {
  color: #67c23a;
}

.result-status.failed {
  color: #f56c6c;
}

.result-message {
  color: #606266;
  margin-bottom: 0.5rem;
}

.result-details pre {
  margin: 0;
  padding: 0.5rem;
  background: #f5f7fa;
  border-radius: 0.25rem;
  font-size: 0.85rem;
  color: #303133;
  overflow-x: auto;
}

/* 集成测试 */
.integration-tests {
  background: white;
  border-radius: 0 0 0.5rem 0.5rem;
  overflow: hidden;
}

.integration-item {
  padding: 1.5rem;
  border-bottom: 1px solid #e4e7ed;
}

.integration-item:last-child {
  border-bottom: none;
}

.integration-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;
}

.integration-info h4 {
  margin: 0 0 0.5rem 0;
  color: #303133;
}

.integration-info p {
  margin: 0;
  color: #909399;
  font-size: 0.9rem;
}

.integration-steps {
  margin-bottom: 1rem;
}

.step-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem;
  border-radius: 0.5rem;
  margin-bottom: 0.5rem;
  border-left: 4px solid #e4e7ed;
}

.step-item.step-passed {
  border-left-color: #67c23a;
  background: #f0f9ff;
}

.step-item.step-failed {
  border-left-color: #f56c6c;
  background: #fef0f0;
}

.step-item.step-running {
  border-left-color: #409eff;
  background: #f0f9ff;
}

.step-number {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.9rem;
  font-weight: 500;
  color: #909399;
}

.step-content {
  flex: 1;
}

.step-name {
  color: #303133;
  margin-bottom: 0.25rem;
}

.step-status {
  color: #909399;
  font-size: 0.85rem;
}

.integration-result {
  background: #f8f9fa;
  border-radius: 0.5rem;
  padding: 1rem;
}

.result-summary {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-weight: 500;
}

.result-summary.passed {
  color: #67c23a;
}

.result-summary.failed {
  color: #f56c6c;
}

/* 性能测试 */
.performance-tests {
  background: white;
  border-radius: 0 0 0.5rem 0.5rem;
  overflow: hidden;
}

.performance-item {
  padding: 1.5rem;
  border-bottom: 1px solid #e4e7ed;
}

.performance-item:last-child {
  border-bottom: none;
}

.performance-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;
}

.performance-info h4 {
  margin: 0 0 0.5rem 0;
  color: #303133;
}

.performance-info p {
  margin: 0;
  color: #909399;
  font-size: 0.9rem;
}

.performance-metrics {
  margin-bottom: 1rem;
}

.metric-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
  padding: 0.75rem;
  background: #f8f9fa;
  border-radius: 0.5rem;
}

.metric-label {
  min-width: 120px;
  color: #606266;
  font-size: 0.9rem;
}

.metric-value {
  min-width: 80px;
  font-size: 1.1rem;
  font-weight: 500;
  color: #303133;
}

.metric-value.metric-good {
  color: #67c23a;
}

.metric-value.metric-bad {
  color: #f56c6c;
}

.metric-unit {
  font-size: 0.8rem;
  color: #909399;
  margin-left: 0.25rem;
}

.metric-status {
  flex: 1;
}

.performance-result {
  background: #f8f9fa;
  border-radius: 0.5rem;
  padding: 1rem;
}

.result-grade {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.result-grade.excellent {
  color: #67c23a;
}

.result-grade.good {
  color: #409eff;
}

.result-grade.poor {
  color: #f56c6c;
}

.result-summary {
  color: #606266;
}

/* 测试日志 */
.test-logs {
  background: white;
  border-radius: 0 0 0.5rem 0.5rem;
  overflow: hidden;
}

.log-controls {
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.log-container {
  max-height: 400px;
  overflow-y: auto;
}

.log-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 0.75rem 1.5rem;
  border-bottom: 1px solid #f0f2f5;
  font-size: 0.9rem;
}

.log-item:last-child {
  border-bottom: none;
}

.log-time {
  color: #909399;
  font-size: 0.85rem;
  min-width: 80px;
}

.log-message {
  flex: 1;
  color: #606266;
}

.log-empty {
  text-align: center;
  padding: 3rem;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .test-overview {
    grid-template-columns: 1fr;
  }
  
  .page-header {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }
  
  .header-right {
    flex-direction: column;
    width: 100%;
  }
  
  .section-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }
  
  .test-header,
  .integration-header,
  .performance-header {
    flex-direction: column;
    gap: 1rem;
  }
  
  .metric-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
  
  .log-controls {
    flex-direction: column;
    gap: 1rem;
  }
  
  .param-item {
    flex-direction: column;
    align-items: flex-start;
  }
}

@media (max-width: 480px) {
  .test-stats {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .log-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
}

/* 自定义参数测试样式 */
.custom-params-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
  padding: 1.5rem;
  background: white;
  border-radius: 0 0 0.5rem 0.5rem;
}

.params-input h4,
.params-preview h4 {
  margin: 0 0 1rem 0;
  color: #303133;
  font-size: 1rem;
}

.param-editor {
  margin-bottom: 1rem;
}

.param-actions {
  display: flex;
  gap: 0.5rem;
}

.preview-content {
  background: #f8f9fa;
  border-radius: 0.5rem;
  padding: 1rem;
  min-height: 200px;
}

.param-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.param-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem;
  background: white;
  border-radius: 0.25rem;
  border: 1px solid #e4e7ed;
}

.param-key {
  font-weight: 500;
  color: #303133;
}

.param-value {
  color: #606266;
  font-family: monospace;
  font-size: 0.9rem;
}

.preview-empty {
  text-align: center;
  color: #909399;
  padding: 2rem;
}

.params-test {
  padding: 1.5rem;
  background: white;
  border-top: 1px solid #e4e7ed;
}

.params-test h4 {
  margin: 0 0 1.5rem 0;
  color: #303133;
}

.test-methods {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.test-method {
  padding: 1.5rem;
  background: #f8f9fa;
  border-radius: 0.5rem;
  border: 1px solid #e4e7ed;
}

.test-method h5 {
  margin: 0 0 0.5rem 0;
  color: #303133;
}

.test-method p {
  margin: 0 0 1rem 0;
  color: #606266;
  font-size: 0.9rem;
}

.result-container {
  margin-top: 1rem;
  padding: 1rem;
  background: white;
  border-radius: 0.5rem;
  border: 1px solid #e4e7ed;
}

.result-link {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.result-params pre {
  margin: 0;
  padding: 0.75rem;
  background: #f5f7fa;
  border-radius: 0.25rem;
  font-size: 0.85rem;
  color: #303133;
  overflow-x: auto;
}

.result-status {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.result-status.passed {
  color: #67c23a;
}

.result-status.failed {
  color: #f56c6c;
}

.result-message {
  color: #606266;
  margin-bottom: 0.5rem;
}

.result-comparison {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.comparison-item {
  padding: 0.75rem;
  background: #f5f7fa;
  border-radius: 0.25rem;
  border: 1px solid #e4e7ed;
}

.comparison-item strong {
  display: block;
  margin-bottom: 0.5rem;
  color: #303133;
}

.comparison-item pre {
  margin: 0;
  font-size: 0.85rem;
  color: #606266;
  overflow-x: auto;
}

.comparison-result {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem;
  border-radius: 0.25rem;
  font-weight: 500;
}

.comparison-result.passed {
  background: #f0f9ff;
  color: #67c23a;
  border: 1px solid #b3e19d;
}

.comparison-result.failed {
  background: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fab6b6;
}

@media (max-width: 768px) {
  .custom-params-container {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .test-methods {
    gap: 1rem;
  }
  
  .test-method {
    padding: 1rem;
  }
  
  .result-link {
    flex-direction: column;
  }
}
</style>